/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jbr.simplefoodplan.rest.impl;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.jbr.simplefoodplan.entities.Plan;
import static com.jbr.simplefoodplan.SecuredDatastore.*;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;


/**
 *
 * @author jbr
 */
@Path("/plan/")
public class PlanResource  {
/*
    public PlanResource() {
        System.out.println("PlanResource create. Checking user...");
        System.out.println("User is: " + userService.getCurrentUser());
        if (!userService.isUserLoggedIn())
            throw new NotAllowedException("Not logged in. Please login using /auth/loginUrl");
    }
*/

    final UserService userService = UserServiceFactory.getUserService();

    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/{planId}")
    public Plan getPlan(@PathParam ("planId") Long planId) throws IOException {
        final Plan plan;
        try {
            plan = get(Plan.class, planId);
        } catch (EntityNotFoundException ex) {
            return null;
        }
        if (plan != null)
            plan.setAddDishToPlan(true);

        return plan;

    }

    @DELETE
    @Consumes({"text/plain"})
    @Path("/{planId}")
    public void removePlanById(@PathParam ("planId") Long planId) throws IOException {
        Plan plan = getPlan(planId);
        delete(plan);
    }

    @DELETE
    @Consumes({"application/json", "application/xml"})
    @Path("/{planId}")
    public void removePlan(Plan plan) throws IOException {
        removePlanById(plan.getId());
    }

    @PUT
    @Produces({"application/json", "application/xml"})
    @Consumes({"application/json", "application/xml"})
    @Path("/{planId}")
    public Plan editPlan(Plan plan, @PathParam ("planId") Long planId) {
        return put(plan);
    }

    @POST
    @Produces({"application/json", "application/xml"})
    @Consumes({"application/json", "application/xml"})
    @Path("/add")
    public Plan addPlan(Plan plan) {
        plan.setAddDishToPlan(true);
        return put(plan);
    }

    /* Mangler lige noget med range i query
    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/list/{fromIncl}/{toExcl}")
    public List<Plan> getAllPlans(@PathParam ("fromIncl") Long fromIncl,
            @PathParam ("toExcl") Long toExcl) throws IOException {
        //final String query = "select from " + Plan.class.getName() + " order by date desc";
        //final Query q = pm.newQuery(query);
        Query query = new Query("plan");
        query.addSort("date", Query.SortDirection.DESCENDING);

        if (fromIncl != null && toExcl != null)
            query.setRange(fromIncl, toExcl);
        List<Plan> plans = (List<Plan>) q.execute();
        for (Plan plan : plans)
            plan.setAddDishToPlan(true);
        return plans;
    }
     *
     */

    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/list")
    public List<Plan> getAllPlans() throws IOException {
        Query query = new Query("plan");
        query.addSort("date", Query.SortDirection.DESCENDING);
        List<Plan> plans = getList(Plan.class, query, 3650);
        for (Plan plan : plans)
            plan.setAddDishToPlan(true);
        CacheControl cacheControl = new CacheControl();
        cacheControl.setNoCache(true);
        GenericEntity<List<Plan>> entity = new GenericEntity<List<Plan>>(plans) {};
        //return Response.ok(entity).cacheControl(cacheControl).build();
        return plans;
    }

    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/list/atDate/{date}")
    public List<Plan> getPlans(@PathParam ("date") String string) throws IOException {
        SimpleDateFormat toDate = new SimpleDateFormat("yyyy-MM-dd");
        //final String query = "select from " + Plan.class.getName() +
        //        " where date == dateParam order by date desc ";
        //final Query q = pm.newQuery(query);
        //q.declareImports("import java.util.Date");
        //q.declareParameters("Date dateParam");
        try {
            final Query query = new Query("plan");
            query.addFilter("date", Query.FilterOperator.EQUAL, toDate.parse(string));
            query.addSort("date", Query.SortDirection.DESCENDING);
            List<Plan> plans = getList(Plan.class, query, 20);
            for (Plan plan : plans)
                plan.setAddDishToPlan(true);
            return plans;
        } catch (ParseException ex) {
            System.out.println(ex);
            throw new RuntimeException(ex);
        }
    }

    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/makeaplan")
    public Plan makeaplan() throws IOException {
        if (!userService.isUserLoggedIn())
            throw new RuntimeException("Not logged in. No access");
        //SecuredDatastore pm = Datastore.getPersistenceManager();
        Plan plan = new Plan();
        plan.setDate(new Date());
        plan.setDishId(5L);
        plan.setUser(userService.getCurrentUser());
        put(plan);
        return plan;
    }

    /*
     * {"id":"13","date":"2011-02-23T19:18:48.387Z","dishId":"5","dish":{"id":"5","name":"Frikadeller"}}
     */


}
